package com.linkdood.app.web.rest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linkdood.app.domain.ScheduleTask;
import com.linkdood.app.dto.ScheduleTaskDTO;
import com.linkdood.app.enums.TaskStatusEnum;
import com.linkdood.app.exception.InvalidParamException;
import com.linkdood.app.service.ScheduleTaskService;
import com.linkdood.app.utils.PaginationUtil;
import com.linkdood.app.utils.ResourceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 定时任务
 *
 * @author hycao
 */
@Api(value = "定时任务", tags = {"定时任务"})
@RestController
@RequestMapping("/api/schedule-tasks")
public class ScheduleTaskResource {

    private final ScheduleTaskService scheduleTaskService;

    public ScheduleTaskResource(ScheduleTaskService scheduleTaskService) {
        this.scheduleTaskService = scheduleTaskService;
    }

    @PreAuthorize("@ss.hasPermi('bxy:timingtaskmanager:details','bxy:ddio-setting:index')")
    @ApiOperation(value = "获取指定 id 的定时任务信息")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "id", value = "定时任务 id", required = true, dataType = "String")})
    @GetMapping("/{id}")
    public ResponseEntity<?> getTask(@PathVariable String id) {
        ScheduleTask scheduleTask = scheduleTaskService.getById(id);
        if (scheduleTask == null) {
            throw new InvalidParamException("task");
        }
        return ResponseEntity.ok(scheduleTask);
    }

    @PreAuthorize("@ss.hasPermi('bxy:timingtaskmanager:index')")
    @ApiOperation(value = "查询定时任务信息", notes = "查询条件可以组合使用")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "name", value = "定时任务名", dataType = "String")})
    @GetMapping
    public ResponseEntity<?> getTasks(@RequestParam(value = "jobGroup", required = false) String jobGroup,
                                      @RequestParam(value = "jobName", required = false) String jobName,
                                      @RequestParam(value = "jobStatus", required = false) String jobStatus,
                                      Pageable pageable) {
        LambdaQueryWrapper<ScheduleTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(jobGroup), ScheduleTask::getJobGroupName, jobGroup);
        queryWrapper.like(StringUtils.isNotEmpty(jobName), ScheduleTask::getJobName, jobName);
        if (StringUtils.isNotEmpty(jobStatus)) {
            queryWrapper.eq(ScheduleTask::getJobStatus, TaskStatusEnum.valueOf(jobStatus));
        }

        Page<ScheduleTask> page = scheduleTaskService.pageTasks(queryWrapper, PaginationUtil.getPage(pageable));
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page);
        return new ResponseEntity<>(page.getRecords(), headers, HttpStatus.OK);
    }

    @ApiOperation(value = "删除指定 id 的定时任务")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTask(@PathVariable String id) {
        scheduleTaskService.deleteTask(id);
        return ResponseEntity.ok(ResourceUtil.success());
    }

    @ApiOperation(value = "新增系统定时任务")
    @PostMapping()
    public ResponseEntity<?> createTask(@RequestBody ScheduleTaskDTO task) {
        ScheduleTask scheduleTask = scheduleTaskService.saveTask(task);
        return ResponseEntity.ok(scheduleTask);
    }
    @PreAuthorize("@ss.hasPermi('bxy:timingtaskmanager:edit')")
    @ApiOperation(value = "修改系统定时任务信息")
    @PatchMapping("/{id}")
    public ResponseEntity<?> updateTask(@PathVariable String id, @RequestBody ScheduleTaskDTO task) {
        ScheduleTask oldTask = scheduleTaskService.getById(id);
        ScheduleTask scheduleTask = scheduleTaskService.modifyTaskCron(oldTask, task);
        return ResponseEntity.ok(scheduleTask);
    }
    @PreAuthorize("@ss.hasPermi('bxy:timingtaskmanager:start')")
    @ApiOperation(value = "启动指定 id 的定时任务")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "id", value = "定时任务 id", required = true, dataType = "String")})
    @PatchMapping("/{id}/start")
    public ResponseEntity<?> resumeTask(@PathVariable String id) {
        ScheduleTask scheduleTask = scheduleTaskService.resumeTask(id);
        return ResponseEntity.ok(scheduleTask);
    }
    @PreAuthorize("@ss.hasPermi('bxy:timingtaskmanager:stop')")
    @ApiOperation(value = "暂停指定 id 的定时任务")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "query", name = "id", value = "定时任务 id", required = true, dataType = "String")})
    @PatchMapping("/{id}/pause")
    public ResponseEntity<?> pauseTask(@PathVariable String id) {
        ScheduleTask scheduleTask = scheduleTaskService.pauseTask(id);
        return ResponseEntity.ok(scheduleTask);
    }

}
